package com.boboPlanet.comm.log;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @Description: TODO  监听日志文件的大小变化 或实现 ApplicationEventPublisherAware
 * @Author: mis_wu
 * @Date: 2023/6/30
 * @Company planet
 **/
@Component
public class LogFileListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(@NotNull ContextRefreshedEvent event) {
        // 日志文件的路径
        String filePath = "path/to/log.txt";
        File file = new File(filePath);
        final long[] previousSize = {file.length()};

        // 在应用启动时执行的逻辑
        // 每隔一段时间检查文件大小是否有变化
        new Thread(() -> {
            while (true) {
                try {
                    // 间隔5秒钟检查一次
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                long currentSize = file.length();
                if (currentSize != previousSize[0]) {
                    // 文件大小发生变化
                    LogReaderHandle.readLogs(filePath);

                    previousSize[0] = currentSize;
                }
            }
        }).start();
    }
}
